package controller;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import entity.Books;

import service.BookService;
import tools.Constants;
import tools.PageSupport;

@Controller
public class BookController {

	@Resource
	private BookService bookService;

	private List<Books> list;

	public List<Books> getList() {
		return list;
	}

	public void setList(List<Books> list) {
		this.list = list;
	}

	/**
	 * 查询
	 * 
	 * @param pageIndex
	 * @param bookName
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "select")
	public String getBook(
			@RequestParam(value = "bookName", required = false) String bookName,
			@RequestParam(value = "pageIndex", required = false) String pageIndex,			
			Model model) {
		try {
			// 页面容量
			int pageSize = Constants.pageSize;
			// 当前页面
			Integer currentPageNo = 1;
			if (pageIndex != null) {
				try {
					currentPageNo = Integer.valueOf(pageIndex);
				} catch (NumberFormatException e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			}
			int totalCount = 0;
			try {
				totalCount = bookService.getBookCount();
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			// 总页数（表）
			PageSupport pages = new PageSupport();
			pages.setCurrentPageNo(currentPageNo);
			pages.setPageSize(pageSize);
			pages.setTotalCount(totalCount);
			int totalPageCount = pages.getTotalPageCount();
			// 控制首页和尾页
			if (currentPageNo < 1) {
				currentPageNo = 1;
			} else if (currentPageNo > totalPageCount) {
				currentPageNo = totalPageCount;
			}
			list = bookService.getBook(currentPageNo,pageSize, bookName);
			model.addAttribute("list", list);
			model.addAttribute("totalPageCount", totalPageCount);
			model.addAttribute("currentPageNo", currentPageNo);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return "select";
	}

	/**
	 * 跳转
	 * 
	 * @return
	 */
	@RequestMapping(value = "tiaozhuan")
	public String tiaoZhuan() {
		return "add";
	}

	/**
	 * 新增
	 * 
	 * @param books
	 * @return
	 */
	@RequestMapping(value = "add")
	public String addBook(@ModelAttribute(value = "books") Books books) {
		try {
			books.setCreateDate(new Date());
			bookService.addBook(books);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return "redirect:/select";
	}
}
